package msg

import (
	"context"
	"encoding/json"
	"fmt"
	"gdei_healthy_colly/log"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

// 内部实现
func serverChanMsg(_ context.Context, title, body, key string) (err error) {
	// 拼接URL
	u, err := url.Parse(viper.GetString("ServerChan.Addr"))
	if err != nil {
		log.Logger.Error("[Server酱]", zap.Error(err))
		return
	}
	u.Path = strings.Join([]string{key, "send"}, ".")

	// 拼接内容
	values := url.Values{}
	values.Add("text", title)
	values.Add("desp", fmt.Sprintf("# 内容\n%s\n***\n# 接收者\n%s", body, key))

	// 发送请求
	resp, err := http.PostForm(u.String(), values)
	if err != nil {
		log.Logger.Error("[Server酱]", zap.Error(err))
		return
	}
	defer resp.Body.Close()
	respBody, _ := ioutil.ReadAll(resp.Body)
	respData := make(map[string]interface{})
	if err = json.Unmarshal(respBody, &respData); err != nil {
		log.Logger.Error("[Server酱]", zap.Error(err), zap.ByteString("raw", respBody))
		return
	}

	log.Logger.Info("[Server酱]", zap.Any("resp", respData))
	return
}

// Server酱通知
func ServerChanMsg(ctx context.Context, title, body string) {
	for _, key := range viper.GetStringSlice("ServerChan.Key") {
		go func(_key string) {
			for i := 0; i < 3; i++ {
				if err := serverChanMsg(ctx, title, body, _key); err == nil {
					return
				}
				<-time.After(30 * time.Second)
			}
		}(key)
	}
	return
}
